package com.itheima.service.impl;

import com.itheima.mapper.OptionMapper;
import com.itheima.mapper.QuestionMapper;
import com.itheima.pojo.Option;
import com.itheima.pojo.Question;
import com.itheima.service.QuestionService;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class QuestionServiceImpl implements QuestionService {
    //1. 创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public void add(Question question) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取SurveyMapper
        QuestionMapper mapper = sqlSession.getMapper(QuestionMapper.class);

        //4.调用方法
        mapper.add(question);
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    public List<Question> selectAll(int sid){
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取SurveyMapper
        QuestionMapper mapper = sqlSession.getMapper(QuestionMapper.class);



        List<Question> questions = mapper.selectAll(sid);


        //5. 释放资源
        sqlSession.close();
        return questions;

    }

    public void addOption(Option option){
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取OptionMapper
        OptionMapper mapper = sqlSession.getMapper(OptionMapper.class);

        mapper.add(option);

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    public List<Option> selectOption(int questionId){
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取OptionMapper
        OptionMapper mapper = sqlSession.getMapper(OptionMapper.class);

        List<Option> options = mapper.selectAll(questionId);
        //5. 释放资源
        sqlSession.close();
        return options;
    }
}
